package com.example.wangyuyuan.androidframe.mvp.base;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wangyuyuan.androidframe.R;
import com.example.wangyuyuan.androidframe.listener.OnPermissionCallback;
import com.example.wangyuyuan.androidframe.manager.ActivityStack;
import com.jaeger.library.StatusBarUtil;
import com.zhy.autolayout.AutoLayoutActivity;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by wangyuyuan on 2017/5/9.
 */

public abstract class BaseActivity extends AutoLayoutActivity implements View.OnClickListener {


    protected Context mContext;
    private AlertDialog loadingDialog;
    private View noDataLayout;
    private static OnPermissionCallback callback;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 锁定竖屏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
//        mContext = getActivityContext();
//        / /沉浸式状态栏
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorAccent), 10);

        initView();
        ButterKnife.bind(this);
        initData();
        ActivityStack.push(BaseActivity.this);
    }

    private void initData() {
        findViewById();
        setListener();
        processLogic();
    }


    /**
     * 业务逻辑处理，主要与后端交互
     */
    protected abstract void processLogic();

    /**
     * 设置各种事件的监听器
     */
    protected abstract void setListener();

    /**
     * 加载页面元素
     */
    protected abstract void findViewById();


    /**
     * 初始activity方法
     */
    protected void initView() {
        loadViewLayout();
    }

    /**
     * 加载页面layout
     */
    protected abstract void loadViewLayout();

    /**
     * Activity.this
     */
    protected abstract Context getActivityContext();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStack.pop(this);
    }

    /**
     * 弹出Toast
     */
    public void showToast(String text) {
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public String getVersionName() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    public int getVersionCode() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void showLoading() {
        try {
            hideLoading();
            loadingDialog = new AlertDialog.Builder(this).create();
            loadingDialog.setCanceledOnTouchOutside(false);
            loadingDialog.show();
            Window window = loadingDialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.alpha = 1.0f;//alpha在0.0f到1.0f之间。1.0完全不透明，0.0f完全透明
            lp.dimAmount = 0.4f;//dimAmount在0.0f和1.0f之间，0.0f完全不暗，1.0f全暗
            window.setAttributes(lp);
            window.setBackgroundDrawable(new BitmapDrawable());
            View alertView = LayoutInflater.from(this).inflate(R.layout.layout_loading, null);
            ImageView iv = (ImageView) alertView.findViewById(R.id.ic_loading);
            Animation mAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_loading);
            iv.setAnimation(mAnimation);
            mAnimation.start();
            window.setContentView(alertView);
        } catch (Exception e) {//TODO：异常先捕捉，case：activity为初始化完成？activity销毁？
            e.printStackTrace();
        }
    }

    public void hideLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    /**
     * @param titleContent 显示标题
     * @param isError      是否是加载失败，true加载失败，false暂无数据
     * @return
     */
    public View getNoDataView(String titleContent, boolean isError, final View.OnClickListener listener) {
        noDataLayout = LayoutInflater.from(this).inflate(R.layout.layout_no_data, null);
        RelativeLayout layoutTips = (RelativeLayout) noDataLayout.findViewById(R.id.layout_no_data_tips);

        TextView tvRefresh = (TextView) noDataLayout.findViewById(R.id.tv_title_no_data_click_refresh);
        TextView title = (TextView) noDataLayout.findViewById(R.id.tv_title_no_data_tips);

        tvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onClick(v);
            }
        });
        if (titleContent != null) {
            title.setText(titleContent);
        }
        layoutTips.setVisibility(isError ? View.VISIBLE : View.GONE);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER_VERTICAL;
        noDataLayout.setLayoutParams(params);
        return noDataLayout;
    }

    private void removeView(LinearLayout containerLayout, View contentLayout, View noDataView) {
        if (noDataView != null) containerLayout.removeView(noDataView);
        containerLayout.removeView(contentLayout);
    }

    public void toError(LinearLayout containerLayout, View contentLayout) {
        View noDataView = getNoDataView("很遗憾，没有找到数据", true, this);
        removeView(containerLayout, contentLayout, noDataView);
        containerLayout.addView(noDataView);
    }

    public void toEmpty(LinearLayout containerLayout, View contentLayout) {
        View noDataView = getNoDataView("很遗憾，没有找到数据", false, this);
        removeView(containerLayout, contentLayout, noDataView);
        containerLayout.addView(noDataView);
    }

    public void showContentView(LinearLayout containerLayout, View contentLayout) {
        View noDataView = getNoDataView("很遗憾，没有找到数据", false, this);
        removeView(containerLayout, contentLayout, noDataView);
        contentLayout.setVisibility(View.VISIBLE);
        containerLayout.addView(contentLayout);
    }

    //6.0以上系统申请权限方法
    public static void requestPermision(String[] permissions, OnPermissionCallback onPermissionCallback) {

        if (ActivityStack.getLastActivity() == null) {
            return;
        }

        callback = onPermissionCallback;
        List<String> permissionsList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(ActivityStack.getLastActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission);
            }
        }
        if (!permissionsList.isEmpty()) {
            ActivityCompat.requestPermissions(ActivityStack.getLastActivity(), permissionsList.toArray(new String[permissionsList.size()]), 1);
        } else {
            if (callback != null) {
                callback.onGranted();
            }
        }
    }

    //6.0以上系统权限申请处理回调结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            List<String> deniedPermissions = new ArrayList<>();
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(permissions[i]);
                }
            }
            if (deniedPermissions.isEmpty()) {
                if (callback != null) {
                    callback.onGranted();
                }
            } else {
                if (callback != null) {
                    callback.onDenied(deniedPermissions);
                }
            }
        }
    }


    public void jumpToActivity(Intent intent) {
        startActivity(intent);
    }

    public void jumpToActivity(Class activity) {
        Intent intent = new Intent(this, activity);
        startActivity(intent);
    }

//    public void jumpToWebViewActivity(String url) {
//        Intent intent = new Intent(this, WebViewActivity.class);
//        intent.putExtra("url", url);
//        jumpToActivity(intent);
//    }


    public void jumpToActivityAndClearTask(Class activity) {
        Intent intent = new Intent(this, activity);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    public void jumpToActivityAndClearTop(Class activity) {
        Intent intent = new Intent(this, activity);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

}